package com.xframe.common.core.export;

import com.xframe.common.core.constant.ExportFormat;
import com.xframe.common.core.dto.DownFileDto;
import com.xframe.common.core.dto.ErrorCode;
import com.xframe.common.core.exception.BusinessException;
import com.xframe.xdal.core.serialize.JsonConfig;
import com.xframe.xdal.core.serialize.JsonConfigContainer;
import com.xframe.xdal.core.serialize.JsonModel;
import com.xframe.xdal.core.serialize.lang.LanguageEnvironmentContext;
import com.xframe.xdal.core.util.UUIDCreateUtil;
import com.xframe.xdal.core.util.XReflect;
import com.xframe.xdal.core.util.pdf.TableCol;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 功能描述:导出文件excel(2017以后的版本)
 *
 * @author xufeng
 * @version 1.0
 * 2022-09-26
 */
public class BuilderFileToExcel implements IBuilderFileTo{

    static final String FILE_EXTENSION = ".xlsx";


    private void getRefHeadList(String language,String ver,String queryKey,String modelCode,List<TableCol> tableColList,String refAttName){
        JsonConfig refJsonConfig = JsonConfigContainer.getConfigContainer().getJsonConfig(language,ver,
                modelCode,queryKey);
        if(refJsonConfig == null){
            return;
        }
        int index = 1;
        for (JsonModel jsonModel : refJsonConfig.getJsonModelList()) {
            if(jsonModel.isRefModel()){
                if(jsonModel.isRefModel()){
                    // 如果是引用模型
                    getRefHeadList(language,ver,jsonModel.getFlag(),jsonModel.getRefModelCode(),tableColList,refAttName + "." +jsonModel.getMapName());
                }
            }else {
                String headName = LanguageEnvironmentContext.getInstance().getModelAttrText(language, modelCode, jsonModel.getMapName(),jsonModel.getHeader());
                TableCol tableCol = new TableCol(headName, refAttName + "." + jsonModel.getMapName(), index);
                tableColList.add(tableCol);
            }
            index++;
        }
    }


    @Override
    public DownFileDto builderFile(List<JsonModel> headList, Collection values, String filePath, String language, String modelCode
            ,String ver,String queryKey) {

        try {
            List<TableCol> tableColList = new ArrayList<>();
            int index = 1;
            for (JsonModel jsonModel : headList) {
                if(jsonModel.isRefModel()){
                    if(jsonModel.isRefObj()){
                        // 如果是引用模型
                        getRefHeadList(language,ver,jsonModel.getFlag(),jsonModel.getRefModelCode(),tableColList,jsonModel.getMapName());
                    }
                }else {
                    String headName = LanguageEnvironmentContext.getInstance().getModelAttrText(language, modelCode, jsonModel.getMapName(),jsonModel.getHeader());
                    TableCol tableCol = new TableCol(headName, jsonModel.getMapName(), index);
                    tableColList.add(tableCol);
                }
                index++;
            }

            SXSSFWorkbook workbook = new SXSSFWorkbook();//创建Excel文件(Workbook)
            SXSSFSheet sheet = workbook.createSheet("sheet1");//创建工作表(Sheet)

            SXSSFRow row = sheet.createRow(0);// 创建行,从0开始
            index = 0;
            for (TableCol tableCol : tableColList) {
                CellStyle style = workbook.createCellStyle();
                style.setDataFormat(workbook.createDataFormat().getFormat("@"));
                sheet.setDefaultColumnStyle(index, style);
                SXSSFCell cells = row.createCell(index);// 设置单元格内容,重载
                setCellStyle(workbook, cells, true).setCellValue(tableCol.getHeadName());
                index++;
            }

            index = 1;
            for (Object entry : values) {
                SXSSFRow itemRow = sheet.createRow(index);
                int cellIndex = 0;
                for(TableCol tableCol : tableColList){
                    Object value = XReflect.getFieldValueByAttrPath(entry,tableCol.getAttrName());
                    SXSSFCell itemCell = itemRow.createCell(cellIndex);
                    setCellStyle(workbook,itemCell,false);
                    itemCell.setCellValue(String.valueOf(value));
                    cellIndex++;
                }
                index++;
            }
            String uuid = UUIDCreateUtil.getUUID().toString();
            String fileName = uuid + FILE_EXTENSION;
            String fileFullName = filePath + fileName;

            saveToPath(workbook,fileFullName);
            DownFileDto dto = new DownFileDto();
            dto.setFileName(uuid);
            dto.setFileFormat(ExportFormat.XLSX.toString().toLowerCase());
            dto.setModelCode(modelCode);
            dto.setLanguage(language);
            return dto;
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.EXPORT_ERROR,e.getMessage());
        }
    }

    /**
     * 保存到路径磁盘
     */
    private void saveToPath(SXSSFWorkbook workbook,String path) throws IOException {

        FileOutputStream out = new FileOutputStream(path);
        workbook.write(out);
        out.close();
        workbook.close();

    }



    private static CellStyle cellStyle;

    private static CellStyle headCellStyle;


    private static void createSXSSFCell(SXSSFWorkbook workbook,boolean isHead){
        //创建CellStyle或HSSFCellStyle对象
        CellStyle style = workbook.createCellStyle();

        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        if(isHead){
            style.setFillForegroundColor(IndexedColors.WHITE.index);
            style.setAlignment(HorizontalAlignment.CENTER);
        }else {
            style.setFillForegroundColor(IndexedColors.WHITE.index);
            style.setAlignment(HorizontalAlignment.LEFT);
        }

        //设置单元格字体位置垂直方向
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        //设置边框
        style.setBorderBottom(BorderStyle.THIN);   //底部边框样式
        //通过颜色索引设置底部颜色
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); //底部边框颜色

        //同理，设置左边样式
        style.setBorderLeft(BorderStyle.THIN);    //左边边框样式
        style.setLeftBorderColor(IndexedColors.BLACK.getIndex());    //左边边框颜色

        //同理，设置右边样式
        style.setBorderRight(BorderStyle.THIN);
        style.setRightBorderColor(IndexedColors.BLACK.getIndex());
        //最后，设置顶部样式
        style.setBorderTop(BorderStyle.THIN);
        style.setTopBorderColor(IndexedColors.BLACK.getIndex());
        //设置字体
        Font font = workbook.createFont();
        font.setFontHeightInPoints((short) 12); // 字体高度
        font.setFontName("微软雅黑"); // 字体
        font.setBold(isHead);
        style.setFont(font);
        if(isHead){
            headCellStyle = style;
        }else {
            cellStyle = style;
        }
    }

    /**
     * 样式1
     *
     * @param workbook
     * @param cell
     * @return
     */
    private static SXSSFCell setCellStyle(SXSSFWorkbook workbook, SXSSFCell cell,boolean isHead) {
        //创建CellStyle或HSSFCellStyle对象
        if(cellStyle == null){
            createSXSSFCell(workbook,false);
        }
        if(headCellStyle == null){
            createSXSSFCell(workbook,true);
        }
        if(isHead) {
            cell.setCellStyle(headCellStyle);
        }else {
            cell.setCellStyle(cellStyle);
        }
        return cell;
    }



}
